var Q = require('q');

function fromCallback(fn) {
  return Q.Promise(function(resolve, reject) {
    try {
      return fn(function(err, data, res) {
        if (err) {
          err.res = res;
          return reject(err);
        }
        return resolve(data);
      });
    } catch (err) {
      return reject(err);
    }
  });
}

var consul = require('consul')({
  promisify: fromCallback
});


var nats = require('nats');
// var async = require('async');
// var dw = require('./index.js');
// var fs = require('fs');


var queue_service_name = 'queue_service';
var task_queue_name = 'download_task_queue';
var queue_service_address = null;
var ResponseQueueName = 'download_response';

var url = process.argv[2];
var projectId = process.argv[3];

function start() {
  console.log(url);
  console.log(projectId);
  getQueueService(queue_service_name)
    .then(function(address) {
      console.log(address);
      queue_service_address = address;
      var opts = {
        url: 'nats://' + queue_service_address
      }
      nats = nats.connect(opts);
      ResponseQueueName = ResponseQueueName + projectId;
      var task = {
        ProjectId: projectId,
        Url: url,
        SaveAddress: __dirname + '/html/',
        ResponseQueueName: ResponseQueueName
      }
      console.log(task);
      console.log(task_queue_name);
      nats.request(task_queue_name, JSON.stringify(task), {
        'max': 1
      }, function(res) {
        if (!res) {
          console.log('fail')
        }
        console.log(res);
      })
    // nats.publish(task_queue_name, JSON.stringify(task), function() {
    //   console.log(arguments);
    // });
    // nats.subscribe(ResponseQueueName, function(msg) {
    //   console.log(JSON.parse(msg.toString()));
    // })
    // process.exit();
    }).catch(function(e) {
    console.error(e);
    console.log('existing');
    process.exit();
  })
}

function getQueueService(name, cb) {
  var defer = Q.defer();
  consul.agent.service.list(function(e, list) {
    var node = list[name];
    if (!node) {
      return defer.reject(new Error('service no exists'));
    }
    var address = '';
    address += node.Address ? node.Address : "localhost";
    address += node.Port ? ':' + node.Port : '';
    return defer.resolve(address);
  })
  return defer.promise;
}

start();
/*
task:
{
  ProjectId:'***',
  ResponseQueueName:'***',
  SaveAddress:'***',
  Url:'***',
  RequestOptions:{}
}
*/
